package pingpongdojo.auth;

import java.util.Map;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.commands.ICommandService;
import org.eclipse.ui.commands.IElementUpdater;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.menus.UIElement;
import org.eclipse.ui.services.ISourceProviderService;

import pingpongdojo.model.ModelFactory;
import pingpongdojo.model.User;

public class LoginHandler extends AbstractHandler implements IElementUpdater {
	final String INVALID_LOGIN = "Invalid user name or password. Please try again!";

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {

		// perform login here ...
		// new LoginForm();
		String msgToUser = "";
		Shell parentShell = HandlerUtil.getActiveShell(event);
		int ret = Window.OK;
		while (ret == Window.OK) {
			LoginDialog dialog = new LoginDialog(parentShell);
			dialog.create();
			if (msgToUser.length() > 0)
				dialog.setErrorMessage(msgToUser);
			ret = dialog.open();
			String login = dialog.getLogin();
			if (login != null && login.length() > 1) {
				// check if the user exist
				User user = ModelFactory.getInstance().getUserManager()
						.getUser(login);
				if (user == null) {
					msgToUser = INVALID_LOGIN;
					continue;
				}
				// check the password
				if (user.getPassword().compareTo(dialog.getPassword()) != 0) {
					msgToUser = INVALID_LOGIN;
					continue;
				}
				// set the user context
				ModelFactory.getInstance().getUserManager()
						.setCurrentUser(user);
				IWorkbenchWindow window = HandlerUtil
						.getActiveWorkbenchWindow(event);
				ISourceProviderService service = (ISourceProviderService) window
						.getService(ISourceProviderService.class);
				SessionSourceProvider sessionSourceProvider = (SessionSourceProvider) service
						.getSourceProvider(SessionSourceProvider.SESSION_STATE);

				// update the source provider
				sessionSourceProvider.setLoggedIn(true);

				// Update the login/logout menu
				ICommandService commandService = (ICommandService) PlatformUI
						.getWorkbench().getService(ICommandService.class);

				commandService.refreshElements(
						"pingpongdojo.auth.sessionCommand", null);

				return null;
			}
		}

		// cancel was hit
		return null;
	}

	@Override
	public void updateElement(UIElement element, Map parameters) {
		element.setText("Login");
	}

}